import express from 'express';
import session from 'express-session';
import webpack from 'webpack';
import bodyParser from 'body-parser';
import config from '../../webpack.config';
import { Config } from './config';
import ssrMiddleware from './ssrMiddleware';
import apiMiddleware from './apiMiddleware';

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(session({
    name: 'MyBlog',
    secret: 'sjhkv343jkkj@jjk',
    cookie: ({ maxAge: 120 * 60000 }),
    resave: true,
    saveUninitialized: false
}));

if (process.env.NODE_ENV !== 'production') {
    // webpack compile
    const compiler = webpack(config);
    const options = {
        publicPath: config.output.publicPath,
        noInfo: true,
        stats: { colors: true },
    };
    app.use(require('webpack-dev-middleware')(compiler, options));
    app.use(require('webpack-hot-middleware')(compiler));
}
app.use(apiMiddleware);
app.use(ssrMiddleware);
app.use((req, res) => {
    res.status(404);
    res.send('not found');
});

app.use((error, req, res) => {
    res.status(500);
    res.render('error', { error });
});

app.disable('x-powered-by');

const server = app.listen(Config.port, () => {
    const { port } = server.address();
    console.info(`Listened at http://localhost:${port}`);
});